package eip.chapter10.processmanager.handler;

import org.apache.log4j.Logger;
import org.jbpm.graph.def.ActionHandler;
import org.jbpm.graph.exe.ExecutionContext;

import eip.chapter10.processmanager.DivingBooking;
import eip.chapter10.processmanager.DivingRequest;
import eip.chapter10.processmanager.ScubaDivingBooking;
import eip.chapter10.processmanager.ScubaDivingRequest;
import eip.util.JibxUtil;

public abstract class AbstractDivingAgencyHandler implements ActionHandler {
	
	private final static Logger logger = Logger.getLogger(AbstractDivingAgencyHandler.class);
	private String target;

	public void execute(ExecutionContext execContext) throws Exception {
		ScubaDivingRequest bookingRequest = (ScubaDivingRequest) 
			execContext.getContextInstance().getVariable("booking");
		DivingRequest divingRequest = new DivingRequest();
		divingRequest.setHotelName("SleepingBeauty");
		divingRequest.setBookingName(bookingRequest.getGuestName());
		divingRequest.setNumberOfDivers(bookingRequest.getNumberOfDivers());
		divingRequest.setRequestDate(bookingRequest.getRequestDate());
		fillTarget();
		Object responseObject = MuleConnector.invokeRequestResponse(target, JibxUtil.marshall(divingRequest));
		logger.info("responseObject " + responseObject);
		DivingBooking divingBooking = (DivingBooking) JibxUtil.unmarshall(responseObject.toString(), DivingBooking.class);
		ScubaDivingBooking bookingResponse = new ScubaDivingBooking(); 
		bookingResponse.setDivingBookingID(divingBooking.getDivingBookID());
		bookingResponse.setDivingStartingTime(divingBooking.getDivingStartingTime());
		bookingResponse.setDivingEndTime(divingBooking.getDivingEndTime());
		bookingResponse.setInstructorName(divingBooking.getInstructorName());
		bookingResponse.setSchoolAddress(divingBooking.getAddress());
		bookingResponse.setTotalPrice(divingBooking.getPrice());
		fillResponse(bookingResponse);
		execContext.getContextInstance().setVariable("bookingResponse", bookingResponse);
		execContext.leaveNode();
	}
	
	protected abstract void fillTarget();
	
	protected abstract void fillResponse(ScubaDivingBooking bookingResponse);

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}
}
